FS : File system
The fs module provides many interfaces for applications to access disk files.
User can use the following code to import the fs
module.
var fs = require('fs');
Support
The following shows fs
module APIs available for each permissions.
User Mode | Privilege Mode | |
---|---|---|
fs.access | ● | ● |
fs.exists | ● | ● |
fs.open | ● | ● |
fs.unlink | ● | ● |
fs.rename | ● | ● |
fs.readFile | ● | ● |
fs.readString | ● | ● |
fs.writeFile | ● | ● |
fs.appendFile | ● | ● |
fs.load | ● | ● |
fs.store | ● | ● |
fs.copy | ● | ● |
fs.stat | ● | ● |
fs.chmod | ● | ● |
fs.chown | ● | |
fs.truncate | ● | ● |
fs.utimes | ● | ● |
fs.compare | ● | ● |
fs.size | ● | ● |
fs.walk | ● | ● |
fs.mkdir | ● | ● |
fs.rmdir | ● | ● |
fs.clrdir | ● | ● |
fs.readdir | ● | ● |
fs.dumpdir | ● | ● |
fs.mkdtemp | ● | ● |
fs.realpath | ● | |
fs.symlink | ● | |
fs.readlink | ● | |
fs.sync | ● | |
fs.format | ● | |
fs.isFormatted | ● | |
fs.tmpname | ● | ● |
fs.tmpfile | ● | ● |
fs.umount | ● | |
fs.transmode | ● | |
fs.File | ● | ● |
file.close | ● | ● |
file.read | ● | ● |
file.write | ● | ● |
file.size | ● | ● |
file.tell | ● | ● |
file.seek | ● | ● |
file.stat | ● | ● |
file.sync | ● | ● |
file.chmod | ● | ● |
file.chown | ● | |
file.truncate | ● | ● |
file.allocate | ● | ● |
file.compare | ● | ● |
file.utimes | ● | ● |
file.toString | ● | ● |
fs.watch | ● | |
watch.ref | ● | |
watch.unref | ● | |
watch.close | ● |
Fs Object
fs.access(path, flags)
path
{String} File path.flags
{Integer} Must befs.F_OK
,fs.R_OK
,fs.W_OK
orfs.X_OK
.- Returns: {Boolean} Return true to indicate access, otherwise false.
Check if the specified file is accessible.
fs.F_OK
Whether the file exists.fs.R_OK
Whether the file is readable.fs.W_OK
Whether the file is Writable.fs.X_OK
Whether the file is executable.
Example
if (fs.access('./test.js', fs.X_OK)) {
console.log('./test.js executable.');
}
fs.exists(path)
path
{String} File path.- Returns: {Boolean} Returns true if the file exists, false otherwise.
Same as fs.access(path, fs.F_OK)
;
Example
if (fs.exists('./test.js')) {
console.log('./test.js exists.');
}
fs.open(path, [flags[, mode]])
path
{String} File path.flags
{String} Open flags, detailed in the following. default:'r'
.mode
{Integer} If it is a new file, specify the file permissions. default:0o666.- Returns: {Object} Returns file object.
Open or create file and return the file object. If the open fails, the return value is undefined
, you can use console.log(sys.error(sys.errno))
to display the error message.
flags
is a string, Must be combination of following string:
flags | Description |
---|---|
r | Opens file for reading. Fail if the file does not exist. |
r+ | Opens file for reading and writing. Fail if the file does not exist. |
w | Creates or opens file for writing. The file is truncate and overwritten if it exists. |
wx | Creates file for writing. Fail if it exists. |
w+ | Creates or open file for reading and writing. The file is truncate and overwritten if it exists. |
wx+ | Creates file for reading and writing. Fail if it exists. |
c | Creates or opens file for writing. |
c+ | Creates or opens file for reading and writing. Overwritten if it exists. |
a | Opens file for appending. Fail if the file does not exist. |
ax | Opens file for appending. Fail if it exists. |
a+ | Opens file for reading and appending. The file is created if it does not exist. |
ax+ | Opens file for reading and appending. Fail if it exists. |
mode
is usually an octal number, When create a new file, it controls the read, write and execute permissions of the file. mode
is divided into three fields, representing the current user, group user, and other user's permission. For details, please refer to the UNIX operating system file permissions related articles. Usually set to 0o666
. Only privileged mode allows setting execution permissions.
Example
// Create a new file to write.
var file = fs.open(path, 'w');
// Create a new file to read / write.
var file = fs.open(path, 'w+');
// Create a new file to read / write if not exist.
var file = fs.open(path, 'wx+');
// Open a file for reading.
var file = fs.open(path, 'r');
// Open a file for reading / writing.
var file = fs.open(path, 'r+');
// Open a file and append reading / writing.
var file = fs.open(path, 'a+');
fs.unlink(path)
path
{String} File path.- Returns: {Boolean} Return true if remove success, otherwise false.
Remove file. If the file is already open when this function is called, it is automatically deleted when the file is last closed.
fs.rename(oldPath, newPath)
oldPath
{String} Original file name.newPath
{String} New file name.- Returns: {Boolean} Return true if remove success, otherwise false.
fs.rename
can not only change the file name, but also move the file location on the same logical volume.
Example
// rename
fs.rename('aaa', 'bbb');
// move
fs.mkdir('dir');
fs.rename('bbb', 'dir/bbb');
fs.readFile(path[, encode])
path
{String} File path.encode
{String} Encoding. default: raw binary data.- Returns: {Buffer} | {String} File reading result.
Read the entire contents of a file from the specified path. If encode
is not specified, the original binary data of the file is returned by a buffer
object. Otherwise, this function automatically converts the contents of the file system to a string of the specified encode
. encode
support: 'utf-8', 'base64', 'hex'.
Example
var buf = fs.readFile(path); // Return Buffer object.
var str = fs.readFile(path, 'utf-8'); // Return a string.
fs.readString(path)
path
{String} File path.- Returns: {String} File reading result.
Read the contents of the file from the specified path and return the file content string. You must ensure that the file content is 'utf-8' string encoding. This function executes faster than fs.readFile()
.
Example
var str = fs.readString(path);
fs.writeFile(path, string[, mode])
path
{String} File path.string
{String} Content to write.mode
{Integer} File create mode. default: 0o666.- Returns: {Boolean} Whether all data is successfully written.
Write a string
to a file use 'utf-8' encode. If there is no file exist in the specified path, a new file will be created. After write complete, truncates the file to the number of bytes written.
Example
fs.writeFile(path, 'Test String.');
fs.writeFile(path, buffer[, offset[, length[, mode]]])
path
{String} File path.buffer
{Buffer} Write data buffer.offset
{Integer} Buffer offset. default:0.length
{Integer} Write length. default:buffer.length.mode
{Integer} File create mode. default: 0o666.- Returns: {Boolean} Whether all data is successfully written.
Write binary data to a file. If there is no file exist in the specified path, a new file will be created. After write complete, truncates the file to the number of bytes written.
Example
fs.writeFile(path, buf);
fs.appendFile(path, buffer[, offset[, length[, mode]]])
Append string or binary data to a file. If there is no file exist in the specified path, a new file will be created. Arguments function is consistent with fs.writeFile
. This method is available in EdgerOS 1.8.9 and later.
fs.load(path[, def])
path
{String} File path.def
{Object} The default object returned if load fails. default: undefined.- Returns: {Object} Object saved in the specified file.
Applications often need to save configuration objects, fs.load()
provides a simple processing method to load configuration in JSON format.
Example
var conf = fs.load('./conf.json');
// Load configure with default setting
var conf = fs.load('./conf.json', { a: 1, b: 2 });
fs.store(path, obj)
path
{String} File path.obj
{Object} Objects to be stored.- Returns: {Boolean} Whether the object is successfully stored.
Convert a configuration object to JSON format and save it in a specified file, and use it with fs.load()
for simple configuration saving and loading.
Example
var store = { a: 1, b: 2 };
fs.store('./conf.json', store);
var conf = fs.load('./conf.json');
console.log('a:', conf.a, 'b:', conf.b);
fs.copy(destPath, srcPath[, cover])
destPath
{String} Target file or path.srcPath
{String} Source file or path.cover
{Boolean} Whether cover the target.- Returns: {Boolean} Whether the copy is successful.
This function can copy files or directories and support recursive subdirectory copy when copying directories.
When srcPath
is a file, if the destPath
file exists, if cover
is true, the target file content will be overwritten, if cover
is false, fs.copy
will return false, if the destPath
file not exists, a new file will be created.
When srcPath
is a directory, if the destPath
is an existing file, an exception will be thrown. If the destPath
directory does not exist, a new directory will be created for copy operation. If the destPath
directory exists, if cover
is true, copy the contents of the source directory to the target directory. If cover
is false, create a subdirectory in the target directory, and then copy the contents of source directory to the newly created subdirectory.
Example
fs.copy('./dest', './src');
fs.stat(path[, followLink])
path
{String} File path.followLink
{Boolean} If the target is link file, do we follow links. default: true.- Returns: {Object} File state object.
Get file or directory state. File state object includes:
dev
Device ID of device containing file.ino
File inode number.mode
File mode, The file type can be judged by this member.nlink
Number of hard links to the file.uid
User ID of file.gid
Group ID of file.size
File size in bytes.atime
Time of last access (millisecond from 1970-01-01 00:00:00 UTC).mtime
Time of last modification (millisecond from 1970-01-01 00:00:00 UTC).ctime
Time of last status change (millisecond from 1970-01-01 00:00:00 UTC).blksize
I/O block size.blocks
Number of blocks allocated.
The file type can be judged by the mode
member:
fs.S_ISDIR(mode)
If true it is a directory.fs.S_ISCHR(mode)
If true it is a character device.fs.S_ISBLK(mode)
If true it is a block device.fs.S_ISREG(mode)
If true it is general data file.fs.S_ISLNK(mode)
If true it is link file.fs.S_ISFIFO(mode)
If true it is fifo / pipe file.fs.S_ISSOCK(mode)
If true it is socket file.
atime
, mtime
and ctime
is in millisecond, You can new Date(...)
to JavaScript standard time.
Same as file.stat()
but use path as argument.
Example
function isDirectory(path) {
var state = fs.stat(path);
if (!state) {
throw new Error('Can not get state!');
}
if (fs.S_ISDIR(state.mode)) {
return true;
} else {
return false;
}
}
function isFile(path) {
var state = fs.stat(path);
if (!state) {
throw new Error('Can not get state!');
}
if (fs.S_ISREG(state.mode)) {
return true;
} else {
return false;
}
}
File state object also has the following methods to get the file type:
isBlockDevice
{Function} Whether it is a block device file.isCharacterDevice
{Function} Whether it is a character device file.isDirectory
{Function} Whether it is a directory.isFIFO
{Function} Whether it is a FIFO device file.isFile
{Function} Whether it is a Ordinary data file.isSocket
{Function} Whether it is a socket file.isSymbolicLink
{Function} Whether it is a symbolic link file.
Example
function isDirectory(path) {
var stat = fs.stat(path);
if (!state) {
throw new Error('Can not get state!');
}
return state.isDirectory();
}
function isFile(path) {
var stat = fs.stat(path);
if (!state) {
throw new Error('Can not get state!');
}
return state.isFile();
}
fs.chmod(path, mode)
path
{String} File path.mode
{Integer} New mode.- Returns: {Boolean} Whether the mode set is successful.
Set file or directory permissions. Only privileged mode allows setting execution permissions.
Example
// Set the file to read-only
fs.chmod(path, 0o444);
// Set the file to read-write
fs.chmod(path, 0o666);
// Set the file to read-write-execute
fs.chmod(path, 0o777);
// Set the file to read-execute
fs.chmod(path, 0o555);
Same as file.chmod()
but use path as argument.
fs.chown(path, uid, gid)
path
{String} File path.uid
{Integer} Host OS user ID.gid
{Integer} Host OS group ID.- Returns: {Boolean} Whether the owner set is successful.
Set file or directory owner. Only privileged mode allows.
Same as file.chown()
but use path as argument.
fs.truncate(path, offset)
path
{String} File path.offset
{Integer} Offset.- Returns: {Boolean} Whether the truncate is successful.
Truncate the file with specified location and discard the outside data.
Example
// The file only retains the first 50 bytes, and the file size becomes 50.
fs.truncate(path, 50);
Same as file.truncate()
but use path as argument.
fs.utimes(path, atime, mtime)
path
{String} File path.atime
{Integer} | {Date} | {String} Access time.mtime
{Integer} | {Date} | {String} Modification time.- Returns: {Boolean} Whether the operation is successful.
Modify file access time and modification time attributes.
Example
fs.utimes(path, null, new Date());
fs.compare(path1, path2)
path1
{String} First file path.path2
{String} Second file path.- Returns: {Boolean} Comparing results.
Compare the contents of two files, return true
if they are the same, otherwise return false
.
fs.size(path)
path
{String} Directory or file path.- Returns: {Integer} Total file size.
If the specified path
is a directory, this function traverses all subdirectories and calculates the sum of all file sizes in the directory. If path
is a file, returns the size of the file, or 0 if path
target information cannot be obtained.
Example
var totalBytes = fs.size(path);
fs.walk(path, func[, arg])
path
{String} Directory path.
This function traverses all subdirectories, Callback function is called for every file or directory in the traversal process.
Example
fs.walk('./dir', function(path, dirent) {
console.log(path + '/' + dirent.name);
});
The dirent object contains the following:
name
{String} File name.type
{Integer} File type. For details, please refer tofs.readdir
.mode
{Integer} File mode.size
{Integer} File size. File only.
mode
and size
are valid only in EdgerOS 2.0 and above.
fs.mkdir(path[, mode[, recursion]])
path
{String} Directory path.mode
{Integer} File mode. default: 0o666.recursion
{Boolean} Whether to recursively fill in the missing directory. default: false.- Returns: {Boolean} Whether create directory is successful.
Create a directory and return false if the directory exists. Otherwise create new directory and returns true.
When recursion
is false, if the intermediate directory is missing, return false, otherwise the intermediate directory is automatically created and returns true.
Example
// Will return false, no './aaa/bbb/ccc' directory exists.
fs.mkdir('./aaa/bbb/ccc/ddd');
// Will return true, './aaa/bbb/ccc' directory create automatically.
fs.mkdir('./aaa/bbb/ccc/ddd', 0o666, true);
fs.rmdir(path[, recursion[, ignoreError]])
path
{String} Directory path.recursion
{Boolean} Whether to recursively delete subfiles. default: false.ignoreError
{Boolean} Whether to continue deleting when an error occurs. default: false.- Returns: {Boolean} Whether remove directory is successful.
Delete a directory. If there are other files or subdirectories in the directory and recursion
is false, it cannot be deleted and returns false. If ignoreError
is false
, an exception will be thrown when an error is encountered.
Example
fs.mkdir('./dir');
fs.mkdir('./dir/aaa');
// Will return false.
fs.rmdir('./dir');
// Will return true.
fs.rmdir('./dir', true);
fs.clrdir(path[, recursion[, ignoreError]])
path
{String} Directory path.recursion
{Boolean} Whether to recursively delete subfiles. default: false.ignoreError
{Boolean} Whether to continue deleting when an error occurs. default: false.- Returns: {Boolean} Whether remove directory is successful.
Clear all files or directories in a directory, recursion
is true
means that recursive cleanup of subdirectories is encountered. If ignoreError
is false
, an exception will be thrown when an error is encountered.
fs.readdir(path, func[, ...arg])
path
{String} Directory path.func
{Function} Perform this callback for each sub file.dirent
{Object} Directory item information....arg
{Any} Arguments.
...arg
{Any} Callback arguments. default: undefined.- Returns: {Boolean} Whether read directory is successful.
Traverse the specified directory. This function does not traverse subdirectories.
dirent
object includes:
name
{String} File name.type
{Integer} File type.
The type
field can be used to determine the file type.
fs.DT_UNKNOWN === type
If true it is unable to determine type.fs.DT_FIFO === type
If true it is fifo / pipe file.fs.DT_CHR === type
If true it is a character device.fs.DT_DIR === type
If true it is a directory.fs.DT_BLK === type
If true it is a block device.fs.DT_REG === type
If true it is general data file.fs.DT_LNK === type
If true it is link file.fs.DT_SOCK === type
If true it is socket file.
fs.DT_UNKNOWN
means that the file system does not support obtaining file types by readdir()
. You must must use stat()
operation to get file type.
Example
fs.readdir(path, function(dirent) {
console.log('File name:', dirent.name);
});
fs.dumpdir(path)
path
{String} Directory path.- Returns: {Array} Object
dirent
array.
Dump all files in specified directory. This function does not traverse subdirectories.
Example
var array = fs.dumpdir(path);
array.forEach(function(dirent, index) {
console.log('File name:', dirent.name);
});
fs.mkdtemp(prefix[, options])
prefix
{String | Buffer} Path prefix.options
{Object} Prefix conversion options.encoding
{String} Conversion encoding. default: 'utf8'.Returns: {String} The created directory name. error returns
undefined
.
Generates six random characters to be appended behind a required prefix
to create a unique temporary directory.
Example
fs.mkdtemp('./foo-');
// returns: './foo-itXde2' (directory has been created)
fs.mkdtemp('./tmp/');
// returns: './tmp/itXde2' (directory has been created) notice: './tmp' must exist.
This method is available in EdgerOS 1.8.9 and later.
fs.realpath(path)
path
{String} Relative path.- Returns: {String} Absolute path.
Get the absolute path corresponding to the specified relative path.
fs.symlink(actualPath, symPath)
actualPath
{String} Actual path.symPath
{String} Symbol path.- Returns: {Boolean} Whether create symlink is successful.
Create a symbolic link file.
fs.readlink(symPath)
symPath
{String} Symbol path.- Returns: {String} Actual path.
Read the actual path of a symbolic link file.
Example
fs.symlink('./act', './sym');
// act === './act'.
var act = fs.readlink('./sym');
// Equivalent to open './act'.
var file = fs.open('./sym');
fs.sync()
Clean all cached data in the system back to the disk. All open files of the entire operating system will write back data.
fs.format(volume)
volume
{String} File system volume.- Returns: {Boolean} Whether format is successful.
Format the specified volume, this operation is very dangerous! that will clear all data on disk, please use with caution.
fs.isFormatted(volume)
volume
{String} File system volume.- Returns: {Boolean} Whether the volume is formatted.
Check if the specified volume is formatted. Unformatted volumes cannot perform other operations, such as reading and writing files.
fs.tmpname([prefix[, ext]])
prefix
{String} Specified temporary file prefix.ext
{String} Specified extension name.- Returns: {String} Temporary file name.
Get a temporary file name, developer can use this file name to create a temporary file, and need to manually delete it after use.
Example
var fname = fs.tmpname('./foo', '.tmp');
var file = fs.open(fname, 'wx+', 0o600);
fs.tmpfile([prefix[, ext]])
prefix
{String} Specified temporary file prefix.ext
{String} Specified extension name.- Returns: {Object} Returns file object.
Create a temporary file for reading and writing, when the file is closed, the system will automatically delete this file.
Example
var file = fs.tmpfile();
file.close();
// system will automatically delete this file.
fs.umount(volume)
volume
{String} Volume path.- Returns: {Boolean} Whether unmount is successful.
Unmount the specified volume. Make sure that no files in the specified volume are in use.
fs.transmode([mode])
mode
{String} New transaction commit mode.- Returns: {String} Current transaction commit mode.
Set the file system transaction commit mode. This function parameter is not currently exposed.
File Class
new fs.File(path, [flags[, mode]])
path
{String} File path.flags
{Integer} Open flags, detailed in the following. default:'r'
.mode
{Integer} If it is a new file, specify the file permissions. default:0o666.- Returns: {Object} Returns file object.
Same as fs.open()
, but if fails, new fs.File()
will throw an exception.
Example
var file = new fs.File('./test.txt', 'r+');
File Object
file.close()
Close this file and reclaiming file descriptors. If user forgets to call this function, the file descriptor is automatically reclaimed when the object is destroyed.
Example
var file = fs.open(path, 'c');
if (file) {
file.close();
}
file.read(buffer[, offset[, length[, position]]])
buffer
{Buffer} Read data buffer.offset
{Integer} Buffer offset. default:0.length
{Integer} Read length. default:buffer.length.position
{Integer} Position. default: current file position.- Returns: {Integer} The number of bytes actually read.
Read file content. offset
is the offset of the buffer
.
If position
is undefined
, the reading starts from the current file pointer (you can change the current file pointer with file.seek()
), and the file pointer will move forward actually read number of bytes. If position
is a specified number, it will start reading from the position specified by position
, and the reading will not update the current pointer of the file.
Example
var buffer = new Buffer(64);
// Read 64 bytes, return actually read number of bytes.
var num = file.read(buffer);
file.write(string[, position])
string
{String} Content to write.position
{Integer} Position. default: current file position.- Returns: {Integer} The number of bytes actually write.
Write a string
to a file use 'utf-8' encode.
If position
is undefined
, the writing starts from the current file pointer (you can change the current file pointer with file.seek()
), and the file pointer will move forward actually write number of bytes. If position
is a specified number, it will start writing from the position specified by position
, and the writing will not update the current pointer of the file.
Example
file.write('Test Content');
file.write(buffer[, offset[, length[, position]]])
buffer
{Buffer} Write data buffer.offset
{Integer} Buffer offset. default:0.length
{Integer} Write length. default:buffer.length.position
{Integer} Position. default: current file position.- Returns: {Integer} The number of bytes actually write.
Write binary data to a file.
If position
is undefined
, the writing starts from the current file pointer (you can change the current file pointer with file.seek()
), and the file pointer will move forward actually write number of bytes. If position
is a specified number, it will start writing from the position specified by position
, and the writing will not update the current pointer of the file.
Example
file.write(buf);
file.size()
- Returns: {Integer} Current file size.
Get current file size.
file.tell()
- Returns: {Integer} Current file pointer location.
Get current file pointer location.
file.seek(offset[, whence])
offset
{Integer} Offset.whence
{Integer} Where to calculate the offset. default: fs.SEEK_SET.- Returns: {Integer} New file pointer location.
Set the current read and write pointer position of the file. whence
can be:
fs.SEEK_SET
Calculate offset from the beginning of the file.fs.SEEK_CUR
Calculate offset from the current file pointer.fs.SEEK_END
Calculate offset from the end of the file.
Example
// Move the file read and write pointer to the 20 byte offset.
file.seek(20);
console.log(file.tell());
file.stat()
- Returns: {Object} File state object.
Get file state. File state object includes:
dev
Device ID of device containing file.ino
File inode number.mode
File mode, The file type can be judged by this member.nlink
Number of hard links to the file.uid
User ID of file.gid
Group ID of file.size
File size in bytes.atime
Time of last access (millisecond from 1970-01-01 00:00:00 UTC).mtime
Time of last modification (millisecond from 1970-01-01 00:00:00 UTC).ctime
Time of last status change (millisecond from 1970-01-01 00:00:00 UTC).blksize
I/O block size.blocks
Number of blocks allocated.
The file type can be judged by the mode
member:
fs.S_ISDIR(mode)
If true it is a directory.fs.S_ISCHR(mode)
If true it is a character device.fs.S_ISBLK(mode)
If true it is a block device.fs.S_ISREG(mode)
If true it is general data file.fs.S_ISLNK(mode)
If true it is link file.fs.S_ISFIFO(mode)
If true it is fifo / pipe file.fs.S_ISSOCK(mode)
If true it is socket file.
Example
function isDirectory(path) {
var file = fs.open(path, 'r');
if (file) {
throw new Error('Open fail.');
}
var state = file.stat();
file.close();
if (state && fs.S_ISDIR(state.mode)) {
return true;
} else {
return false;
}
}
function isFile(path) {
var file = fs.open(path, 'r');
if (file) {
throw new Error('Open fail.');
}
var state = file.stat();
file.close();
if (state && fs.S_ISREG(state.mode)) {
return true;
} else {
return false;
}
}
atime
, mtime
and ctime
is in millisecond, You can new Date(...)
to JavaScript standard time.
File state object also has the following methods to get the file type:
isBlockDevice
{Function} Whether it is a block device file.isCharacterDevice
{Function} Whether it is a character device file.isDirectory
{Function} Whether it is a directory.isFIFO
{Function} Whether it is a FIFO device file.isFile
{Function} Whether it is a Ordinary data file.isSocket
{Function} Whether it is a socket file.isSymbolicLink
{Function} Whether it is a symbolic link file.
Example
function isDirectory(path) {
var file = fs.open(path, 'r');
if (file) {
throw new Error('Open fail.');
}
var state = file.stat();
file.close();
return state.isDirectory();
}
function isFile(path) {
var file = fs.open(path, 'r');
if (file) {
throw new Error('Open fail.');
}
var state = file.stat();
file.close();
return state.isFile();
}
file.sync([onlyData])
onlyData
{Boolean} Only write back the data. default: false.
Write all the file or only data cached by file system back to the disk.
file.chmod(mode)
mode
{Integer} New mode.- Returns: {Boolean} Whether the mode set is successful.
Set file permissions. Only privileged mode allows setting execution permissions.
Example
// Set the file to read-only
file.chmod(0o444);
// Set the file to read-write
file.chmod(0o666);
// Set the file to read-write-execute
file.chmod(0o777);
// Set the file to read-execute
file.chmod(0o555);
file.chown(uid, gid)
uid
{Integer} Host OS user ID.gid
{Integer} Host OS group ID.- Returns: {Boolean} Whether the owner set is successful.
Set file owner. Only privileged mode allows.
file.truncate(offset)
offset
{Integer} Offset.- Returns: {Boolean} Whether the truncate is successful.
Truncate the file with specified location and discard the outside data.
Example
// The file only retains the first 50 bytes, and the file size becomes 50.
file.truncate(50);
file.allocate(offset, length)
offset
{Integer} Offset.length
{Integer} Length.- Returns: {Boolean} Whether the owner set is successful.
This function shall ensure that any required storage for regular file data starting at offset
and continuing for length
bytes is allocated on the file system storage media. If file.allocate
returns true
, subsequent writes to the specified file data shall not fail due to the lack of free space on the file system storage media.
This feature is valid in EdgerOS 2.0.8 and above, and the SylixOS kernel must be in version 3.2.8 and above.
file.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])
target
{File | String} The target file.targetStart
{Integer} target file start offset. default: 0.targetEnd
{Integer} target file end offset (not include). default: target.size().sourceStart
{Integer} source file start offset. default: 0.sourceEnd
{Integer} source file end offset (not include). default: this.size().- Returns: {Boolean} Comparing results.
Compare the contents of two files, return true
if they are the same, otherwise return false
. If target
is a String
, it means to the target file path.
file.utimes(atime, mtime)
atime
{Integer} | {Date} | {String} Access time.mtime
{Integer} | {Date} | {String} Modification time.- Returns: {Boolean} Whether the operation is successful.
Modify file access time and modification time attributes.
Example
file.utimes(null, new Date());
file.toString([start[, end]])
start
{Integer} File start position. default: 0.end
{Integer} File end position (not includes). default: file.size().- Returns: {String} File reading result.
Read the contents of the file and return the file content string. You must ensure that the file content is 'utf-8' string encoding. This function executes faster than fs.readFile()
. This function does not change the file read and write pointer.
Example
var str = file.toString();
Fs Watcher
JSRE allows create directory watchers to listen file changes in the directory. This feature is available on EdgerOS 2.0.3 and above.
fs.watch(dirname[, options], listener)
dirname
{String} Specified directory.options
{Object} Watching options.recursive
{Boolean} Indicates whether all subdirectories should be watched, or only the current directory. default: false.
listener
{Function} Event listener.event
{String} Event.filename
{String} Filename.origname
{String} When theevent
is'rename'
, indicate the original file name.
- Returns: {FsWatcher} Watcher object.
Create a listener for listening to file changes in the specified directory. The possible event types are as follows:
'create'
File was created.'delete'
File was deleted.'modify'
File was modified.'rename'
File was renamed.'attributes'
File attributes have been modified.
Example
fs.watch('/dir', function(event, filename, origname) {
if (event === 'create') {
console.log('new file:', filename);
} else if (event === 'rename') {
console.log('orig file:', origname, 'renamed to:', filename);
}
});
Fs Watcher Object
watch.ref()
- Returns: {FsWatcher} This object.
References the current object, which prevents the object from being recycled, which has already been done when the watch object is created.
watch.unref()
- Returns: {FsWatcher} This object.
Inverse of watch.ref()
.
watch.close()
Close the watch object, no longer listen for file changes in the specified directory.